#include "CamWhore.h"

CamWhore::CamWhore(QWidget *parent, Qt::WFlags flags)
	: QWidget(parent, flags)
{
	ui.setupUi(this);

	m_dialog = new FacebookLoginDialog(this);

	connect(ui.pushButton, SIGNAL(pressed()), this, SLOT(saveImage()));
	connect(ui.webcamView, SIGNAL(effectAdded(const QString&)), this, SLOT(addEffectToList(const QString&)));
	connect(ui.comboBox, SIGNAL(activated(const QString&)), this, SLOT(effectSelected(const QString&)));
	connect(ui.pushButton_2, SIGNAL(pressed()), this, SLOT(fbItPressed()));
	connect(m_dialog, SIGNAL(done()), this, SLOT(setupFbApi()));

	std::vector<WebcamDevice> devices;
	Webcam::listDevices(devices);

	m_webcam = new Webcam();

	m_settings.load();

	m_effectManager.setGLContext(ui.webcamView->context());
	m_effectManager.loadEffects("Data\\Effects\\Effects.xml");
	populateEffectList();

	m_effectManager.setActiveEffect("Mirror");

	ui.webcamView->setWebcam(m_webcam);

	WebcamDevice dev;

	if(m_settings.getValue("DeviceName") == "__Invalid__")
	{
		// Ask the user for a device
		DeviceSelectionDialog dialog(this);

		for(std::vector<WebcamDevice>::iterator it = devices.begin(); it != devices.end(); ++it)
		{
			dialog.addDevice(QString::fromStdString(it->name));
		}

		dialog.exec();
		
		QString name = dialog.selectedDevice();

		dev.name = name.toStdString();

		m_settings.setValue("DeviceName", name);
		m_settings.save();
	}
	else
	{
		dev.name = m_settings.getValue("DeviceName").toStdString();
	}

	if(!m_webcam->setup(dev))
	{
		QMessageBox message;
		message.setText("Failed to setup webcam device!");
		message.exec();
	}

	if(!m_webcam->start())
	{
		QMessageBox message3;
		message3.setText("Failed to start webcam!");
		message3.exec();
	}
}

CamWhore::~CamWhore()
{
	m_webcam->stop();
	delete m_webcam;
}

int getNextImage(QString dir)
{
	int i = 1;

	bool running = true;
	while(running)
	{
		QString file = dir;
		file += "/CW Picture ";
		file += QString::number(i);
		file += ".png";
		if(!QFile::exists(file))
		{
			running = false;
			continue;
		}

		++i;
	}

	return i;
}

void CamWhore::saveImage()
{	
	if(m_webcam->currentFrame())
	{
		const WebcamFrame* frame = m_webcam->currentFrame();

		QImage image = ui.webcamView->grabFrameBuffer();
		
		QString saveDir = m_settings.getValue("SaveDirectory");

		QDir theDir(saveDir);
		if(!theDir.exists())
		{
			theDir.mkpath(".");
		}

		int i = getNextImage(saveDir);
			
		QString filename(saveDir);
		filename += "/CW Picture ";
		filename += QString::number(i);
		filename += ".png";

		qDebug() << "Saving " << i << " " << filename;
		image.save(filename);
	}
}

void CamWhore::populateEffectList()
{
	const QList<Effect>& effects = m_effectManager.effects();
	for(QList<Effect>::const_iterator it = effects.begin(); it != effects.end(); ++it)
	{
		ui.comboBox->addItem(it->name());
	}
}

void CamWhore::effectSelected(const QString& text)
{

}

void CamWhore::fbItPressed()
{
	//m_fbDialog->init();
	//m_fbDialog->show();
#ifdef BUILD_WITH_FACEBOOK
	m_dialog->setModal(true);
	m_dialog->initAndShow();

	setupFbApi();
#endif
}

void CamWhore::setupFbApi()
{
	QString sessionKey = m_dialog->sessionKey();
	QString uid = m_dialog->uid();
	QString secret = m_dialog->secret();

	qDebug() << "Session Key: " << sessionKey;
	qDebug() << "UID: " << uid;
	qDebug() << "Secret: " << secret;

	m_fbApi.setApiKey("87c0a992da2e73b7990ef3e41d63ec5d");
	m_fbApi.setSessionKey(sessionKey);
	m_fbApi.setUid(uid);
	m_fbApi.setSecret(secret);

	// test it

	QMap<QString, QString> params;
	params["format"] = "JSON";

	m_fbApi.callMethod("auth.createToken", params);
}

void CamWhore::closeFbDialog()
{
	/*
	QNetworkAccessManager* manager = new QNetworkAccessManager(this);
	
	QUrl url("http://facebook.com/restserver.php");
	url.addQueryItem("api_key", "87c0a992da2e73b7990ef3e41d63ec5d");
	url.addQueryItem("v", "1.0");
	url.addQueryItem("format", "JSON");

	QNetworkRequest request;
	request.setUrl(url);

	QNetworkReply* response = manager->get(request);
	qDebug() << "got stuff.\n";

	m_fbDialog->close(); */
}